package tjs.study.antlr.splunkToMysql.v1;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import tjs.study.antlr.splunkToMysql.v1.g4.SplunkToMysqlBaseVisitor;
import tjs.study.antlr.splunkToMysql.v1.g4.SplunkToMysqlLexer;
import tjs.study.antlr.splunkToMysql.v1.g4.SplunkToMysqlParser;

import java.util.List;

public class Do {
    public static void main(String[] args) throws Exception {
        // 输入的Splunk语句
        String splunkQuery = "index mainAlias = table_name |\n table field1, field2, field3";
        // 创建输入流
        CharStream input = CharStreams.fromString(splunkQuery);
        // 创建词法分析器
        SplunkToMysqlLexer lexer = new SplunkToMysqlLexer(input);CommonTokenStream tokens = new CommonTokenStream(lexer);
        // 创建解析器
        SplunkToMysqlParser parser = new SplunkToMysqlParser(tokens);ParseTree tree = parser.query();
        // 自定义的转换器
        SplunkToMySQLConverter converter = new SplunkToMySQLConverter();String mysqlQuery = converter.visit(tree);
        // 输出转换后的MySQL语句
        System.out.println(mysqlQuery);
    }
}
class SplunkToMySQLConverter extends SplunkToMysqlBaseVisitor<String> {
    @Override
    public String visitQuery(SplunkToMysqlParser.QueryContext ctx) {
        String indexName = ctx.indexTable().indexName().getText(), 
                indexAliasName = ctx.indexTable().indexAlias().getText();
        List<SplunkToMysqlParser.FieldNameContext> fields = ctx.fields().fieldName();
        StringBuilder mysqlQuery = new StringBuilder("SELECT ");
        for (int i = 0; i < fields.size(); i++) {
            mysqlQuery.append(fields.get(i).getText());
            if (i < fields.size() - 1) {
                mysqlQuery.append(", ");
            }
        }
        mysqlQuery.append("\n  FROM ").append(indexName).append(" AS ").append(indexAliasName);
        return mysqlQuery.toString();
    }
}
